package com.dhcc.sdc.busi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.RedisUtil;
import com.dhcc.sdc.base.dao.SdcQcCdssLinkMapper;
import com.dhcc.sdc.base.entity.SdcQcCdssLinkEntity;
import com.dhcc.sdc.base.service.ISdcBaseAssessmentService;
import com.dhcc.sdc.base.service.ISdcQcCdssLinkService;
import com.dhcc.sdc.busi.dto.TreatPlanDto;
import com.dhcc.sdc.busi.entity.SdcShowPremiseEntity;
import com.dhcc.sdc.busi.service.ISdcQcService;
import com.dhcc.sdc.busi.service.ISdcShowPremiseService;
import com.dhcc.sdc.cdss.entity.*;
import com.dhcc.sdc.cdss.service.*;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.standard.service.ISdsStandDataSourceService;
import com.dhcc.sds.standard.service.ISdsStandRuleBaseService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 诊疗方案维护
 *
 * @author zhangdc
 * @ClassName: SdcTreatPlanController
 * @Description: TODO
 * @date 2022-08-26 10:10:53
 */
@Controller
@RequestMapping("${sys.backendPath}/sdc/sdctreatplan")
public class SdcTreatPlanController {

    private String PREFIX = "/backend/sdc/sdctreatplan/";

    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdcCdssNursingService cdssNursingService;
    @Autowired
    private ISdcCdssEvalService cdssEvalService;
    @Autowired
    private ISdcCdssExamService cdssExamService;
    @Autowired
    private ISdcCdssLabService cdssLabService;
    @Autowired
    private ISdcCdssTreatService cdssTreatService;
    @Autowired
    private ISdsStandDataSourceService sdsStandSourceService;
    @Autowired
    private ISdcBaseAssessmentService sdcBaseAssessmentService;
    @Autowired
    private ISdcQcService sdcQcService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private ISdcShowPremiseService sdcShowPremiseService;
    @Resource
    private SdcQcCdssLinkMapper sdcQcCdssLinkMapper;
    @Autowired
    private ISdcQcCdssLinkService sdcQcCdssLinkService;
    @Autowired
    private ISdcCdssItemService sdcCdssItemService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ISdsStandRuleBaseService sdsStandRuleBaseService;


    /**
     * 跳转到产品函数库列表首页
     */
    @RequestMapping("")
    public String index(Model model) {
        JSONObject recommendTypeMap = sdsCommonService.getDicMap("CDSSRecommendType");
        //获取病种
        JSONArray entityMap = sdsQcentityService.getUpEntityMap();
        model.addAttribute("recommendTypeMap", recommendTypeMap);
        model.addAttribute("entityMap", entityMap);
        return PREFIX + "sdctreatplan.html";
    }


    @RequestMapping("/list")
    @ResponseBody
    public Object caseList(@RequestParam Map<String, Object> params) {

        if (StringUtils.isEmpty(params.get("recommendType"))) {
            //查询全部类型
            return null;
        } else {
            String recommendType = (String) params.get("recommendType");
            Integer itemType = 0;
            switch (recommendType) {
                case "推荐护理处置":
                    itemType = 5;
                    break;
                    /*Page<SdcCdssNursingEntity> page1 = new PageFactory<SdcCdssNursingEntity>().defaultPage();
                    List<SdcCdssNursingEntity> result1 = this.cdssNursingService.page(page1, params);
                    page1.setRecords((List<SdcCdssNursingEntity>) new EmptyWarpper(result1).warp());
                    return R.packForBT(page1);*/
                case "推荐检验":
                    itemType = 3;
                    break;
                   /* Page<SdcCdssLabEntity> page2 = new PageFactory<SdcCdssLabEntity>().defaultPage();
                    List<SdcCdssLabEntity> result2 = this.cdssLabService.page(page2, params);
                    page2.setRecords((List<SdcCdssLabEntity>) new EmptyWarpper(result2).warp());
                    return R.packForBT(page2);*/
                case "推荐检查":
                    itemType = 2;
                    break;
                    /*Page<SdcCdssExamEntity> page3 = new PageFactory<SdcCdssExamEntity>().defaultPage();
                    List<SdcCdssExamEntity> result3 = this.cdssExamService.page(page3, params);
                    page3.setRecords((List<SdcCdssExamEntity>) new EmptyWarpper(result3).warp());
                    return R.packForBT(page3);*/
                case "推荐治疗方案":
                    itemType = 4;
                    break;
                    /*Page<SdcCdssTreatEntity> page4 = new PageFactory<SdcCdssTreatEntity>().defaultPage();
                    List<SdcCdssTreatEntity> result4 = this.cdssTreatService.page(page4, params);
                    page4.setRecords((List<SdcCdssTreatEntity>) new EmptyWarpper(result4).warp());
                    return R.packForBT(page4);*/
                case "推荐评估量表":
                    itemType = 1;
                    break;
                    /*Page<SdcCdssEvalEntity> page5 = new PageFactory<SdcCdssEvalEntity>().defaultPage();
                    List<SdcCdssEvalEntity> result5 = this.cdssEvalService.page(page5, params);
                    page5.setRecords((List<SdcCdssEvalEntity>) new EmptyWarpper(result5).warp());
                    return R.packForBT(page5);*/

            }
            params.put("itemType", itemType);
            Page<SdcCdssItemEntity> page = new PageFactory<SdcCdssItemEntity>().defaultPage();
            List<SdcCdssItemEntity> result = this.sdcCdssItemService.page(page, params);
            page.setRecords((List<SdcCdssItemEntity>) new EmptyWarpper(result).warp());
            return R.packForBT(page);

        }

    }

    @RequestMapping(value = "/loadLine")
    @ResponseBody
    public Object loadLine(@RequestParam Map<String, Object> params) {
        String entityId = (String) params.get("entityId");
        SdsQcentityEntity sdsQcentity = sdsQcentityService.selectById(entityId);
        return sdsQcentity;
    }

    @RequestMapping("/offLine")
    @ResponseBody
    public Object offLine(@RequestParam Map<String, Object> params) {
        String entityId = (String) params.get("entityId");
        SdsQcentityEntity old = sdsQcentityService.selectById(entityId);
        if (old.getPlanActive() == 0) {
            old.setPlanActive(1);
        } else {
            old.setPlanActive(0);
        }
        old.updateAllColumnById();
        return R.ok();
    }

    @RequestMapping("/to_add")
    public String toAdd(Model model) {
        JSONArray qcEntity = sdsQcentityService.getUpEntityMap();
        //JSONArray recommendTypeMap = sdsCommonService.getDicArray("CDSSRecommendType");
        //采集时机
        JSONObject getValTimeMap = sdsCommonService.getDicMap("ItemGetValTime");
        JSONObject recommendTypeMap = sdsCommonService.getDicMap("CDSSRecommendType");
        model.addAttribute("qcEntityMap", qcEntity);
        model.addAttribute("recommendTypeMap", recommendTypeMap);
        model.addAttribute("getValTimeMap", getValTimeMap);
        return PREFIX + "sdctreatplan_add.html";
    }


    /**
     * 跳转到修改诊疗方案维护
     */
    //@RequestMapping("/to_update/{id}/{recommendType}/{entityId}")
    @RequestMapping("/to_update")
    public String toUpdate(@RequestParam Map<String, Object> params, Model model) {
        String entityId = (String) params.get("entityId");
        String recommendType = (String) params.get("recommendType");
        String id = (String) params.get("id");
        JSONObject getValTimeMap = sdsCommonService.getDicMap("ItemGetValTime");
        JSONObject standSourceMap = sdsStandSourceService.getDataMap();
        JSONArray qcEntity = sdsQcentityService.getUpEntityMap();
        JSONArray qcData = sdcQcService.getJSONArrayByEntityId(Long.parseLong(entityId));
        DictionaryEntity dictionaryEntity = dictionaryService.selectById(Long.parseLong(recommendType));

        model.addAttribute("getValTimeMap", getValTimeMap);
        model.addAttribute("qcEntityMap", qcEntity);
        model.addAttribute("sdcTreatPlanId", Long.parseLong(id));
        model.addAttribute("recommendType", dictionaryEntity.getDescription());
        model.addAttribute("dataSourceMap", standSourceMap);
        model.addAttribute("qcMap", qcData);

        return PREFIX + "sdctreatplan_edit.html";
    }

    /**
     * 初始化诊疗方案
     */
    @RequestMapping(value = "/treatPlan")
    @ResponseBody
    public Object treatPlan(@RequestParam Map<String, Object> params) {
        SdcCdssItemEntity sdcCdssItemEntity = new SdcCdssItemEntity();
        if (!StringUtils.isEmpty(params.get("id")) && !StringUtils.isEmpty(params.get("recommendType"))) {
            String id = (String) params.get("id");
            sdcCdssItemEntity = sdcCdssItemService.selectById(id);

        }
        return sdcCdssItemEntity;
    }

    /**
     * 初始化显示时间段
     */
    @RequestMapping(value = "/showTimeQuantum")
    @ResponseBody
    public Object showTimeQuantum(@RequestParam Map<String, Object> params) {
        SdcCdssItemEntity sdcCdssItemEntity = new SdcCdssItemEntity();
        if (CommonUtil.isNotEmpty(params.get("id"))) {
            String id = (String) params.get("id");
            sdcCdssItemEntity = sdcCdssItemService.selectById(id);
        }
        return sdcCdssItemEntity;
    }

    /**
     * 新增质控规则
     */
    @RequestMapping(value = "/updateTreatPlan")
    @ResponseBody
    public Object updateTreatPlan(TreatPlanDto treatPlanDto) {
        Long id = 0L;
        if (CommonUtil.isOneEmpty(treatPlanDto)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
//        try {
//            treatPlanDto.setParam(java.net.URLDecoder.decode(treatPlanDto.getParam(), "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        String recommendType = treatPlanDto.getRecommendType();
        String cdssNodeId = "";
        //插入or更新
        boolean isInsert = false;
        Integer itemType = 0;
        String redisKey = treatPlanDto.getQcentityId() + "_";
        switch (recommendType) {
            case "推荐护理处置":
                itemType = 5;
                redisKey = redisKey + "RecomNursing";
                break;
            case "推荐检验":
                itemType = 3;
                redisKey = redisKey + "RecomLabExam_lab";
                break;
            case "推荐检查":
                itemType = 2;
                redisKey = redisKey + "RecomLabExam_exam";
                break;
            case "推荐治疗方案":
                itemType = 4;
                redisKey = redisKey + "AssistTreat";
                break;
            case "推荐评估量表":
                itemType = 1;
                redisKey = redisKey + "RecomAssess";
                break;
        }
        // 删除缓存信息
        redisUtil.deleteByKeyWords(redisKey);

        if (StringUtils.isEmpty(treatPlanDto.getId())) {
            SdcCdssItemEntity sdcCdssItemEntity = new SdcCdssItemEntity();
            BeanUtils.copyProperties(treatPlanDto, sdcCdssItemEntity);
            sdcCdssItemEntity.setItemType(itemType);
            sdcCdssItemEntity.setIsCdss(0);
            String idStr = IdWorker.getIdStr();
            sdcCdssItemEntity.setNodeId(idStr);
            sdcCdssItemEntity.setItemId(idStr);
            sdcCdssItemEntity.setNoCondition(1);
            sdcCdssItemEntity.insert();
            cdssNodeId = sdcCdssItemEntity.getNodeId();
            id = sdcCdssItemEntity.getId();
            isInsert = true;
        } else {
            SdcCdssItemEntity old1 = sdcCdssItemService.selectById(treatPlanDto.getId());
            old1.setItemName(treatPlanDto.getItemName());
            old1.setItemDesc(treatPlanDto.getItemDesc());
            old1.setQcentityId(treatPlanDto.getQcentityId());
            old1.setSourceFlag(treatPlanDto.getSourceFlag());
            old1.setNoCondition(treatPlanDto.getNoCondition());
            old1.setDataSource(treatPlanDto.getDataSource());
            old1.setDataSourceItem(treatPlanDto.getDataSourceItem());
            old1.setParam(treatPlanDto.getParam());
            old1.setPushStart(treatPlanDto.getPushStart());
            old1.setPushEnd(treatPlanDto.getPushEnd());
            old1.setTimeUnit(treatPlanDto.getTimeUnit());
            //old1.setQcId(treatPlanDto.getQcId());
            old1.setShowPremise(treatPlanDto.getShowPremise());
            old1.setType(treatPlanDto.getType());
            old1.setIsActive(treatPlanDto.getIsActive());
            old1.updateAllColumnById();
            cdssNodeId = old1.getNodeId();
            isInsert = false;
        }

        if (isInsert) {
            if (!StringUtils.isEmpty(treatPlanDto.getQcId())) {
                SdcQcCdssLinkEntity sdcQcCdssLinkEntity = new SdcQcCdssLinkEntity();
                sdcQcCdssLinkEntity.setCdssNodeId(cdssNodeId);
                sdcQcCdssLinkEntity.setQcItemId(treatPlanDto.getQcId());
                sdcQcCdssLinkEntity.setType(itemType);
                sdcQcCdssLinkEntity.insert();
            }
        } else {
            if (!StringUtils.isEmpty(treatPlanDto.getQcId())) {
                SdcQcCdssLinkEntity sdcQcCdssLinkEntity = sdcQcCdssLinkService.selectByNodeId(cdssNodeId);
                if (!StringUtils.isEmpty(sdcQcCdssLinkEntity)) {
                    sdcQcCdssLinkEntity.setQcItemId(treatPlanDto.getQcId());
                    sdcQcCdssLinkEntity.updateAllColumnById();
                } else {
                    SdcQcCdssLinkEntity sdcQcCdssLinkEntity2 = new SdcQcCdssLinkEntity();
                    sdcQcCdssLinkEntity2.setCdssNodeId(cdssNodeId);
                    sdcQcCdssLinkEntity2.setQcItemId(treatPlanDto.getQcId());
                    sdcQcCdssLinkEntity2.setType(itemType);
                    sdcQcCdssLinkEntity2.insert();
                }
            } else {
                //删除之前的关系
                SdcQcCdssLinkEntity sdcQcCdssLinkEntity = sdcQcCdssLinkService.selectByNodeId(cdssNodeId);
                if (!StringUtils.isEmpty(sdcQcCdssLinkEntity)) {
                    sdcQcCdssLinkEntity.deleteById();
                }
            }
        }

        return R.ok(id.toString());
    }


    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long sdcTreatPlanId, @RequestParam String recommendType) {
        SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemService.selectById(sdcTreatPlanId);
        SdcQcCdssLinkEntity sdcQcCdssLinkEntity5 = sdcQcCdssLinkService.selectByNodeId(sdcCdssItemEntity.getNodeId());
        if (!StringUtils.isEmpty(sdcQcCdssLinkEntity5)) {
            sdcQcCdssLinkEntity5.deleteById();
        }
        String redisKey = sdcCdssItemEntity.getQcentityId() + "_";
        switch (sdcCdssItemEntity.getItemType()) {
            case 1:
                redisKey = redisKey + "RecomAssess";
                break;
            case 2:
                redisKey = redisKey + "RecomLabExam_exam";
                break;
            case 3:
                redisKey = redisKey + "RecomLabExam_lab";
                break;
            case 4:
                redisKey = redisKey + "AssistTreat";
                break;
            case 5:
                redisKey = redisKey + "RecomNursing";
                break;
        }
        redisUtil.deleteByKeyWords(redisKey);
        sdcCdssItemEntity.deleteById();
        return R.ok();
    }


    @RequestMapping(value = "/selectShowPremiseTable")
    @ResponseBody
    public Object selectShowPremiseTable(@RequestParam Map<String, Object> params) {
        //return cdssTreatService.selectByShowPremise(params);
        return sdcCdssItemService.selectByShowPremise(params);
    }

    @RequestMapping(value = "/selectRuleByShowPremise")
    @ResponseBody
    public Object selectRuleByShowPremise(@RequestParam Map<String, Object> params) {
        return sdcShowPremiseService.selectByShowPremise(params);
    }
    @RequestMapping(value = "selectDisplayRule")
    @ResponseBody
    public Object selectAllRule(@RequestParam Map<String,Object> params) {
        return sdsStandRuleBaseService.selectDisplayRule(params);
    }

    @RequestMapping(value = "saveDisplayRule")
    @ResponseBody
    public Object saveDisplayRule(@RequestParam Map<String,Object> params){
        if (!StringUtils.isEmpty(params.get("id"))) {
            String id = (String) params.get("id");
            String displayRule = (String)params.get("displayRule");
            SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemService.selectById(id);
            sdcCdssItemEntity.setShowPremise(displayRule);
            sdcCdssItemEntity.updateAllColumnById();
        }
        return R.ok();
    }

    @RequestMapping(value = "/showDisplayRule")
    @ResponseBody
    public Object showDisplayRule(@RequestParam Map<String,Object> params){
        SdcCdssItemEntity sdcCdssItemEntity = new SdcCdssItemEntity();
        String id = (String) params.get("id");
        sdcCdssItemEntity = sdcCdssItemService.selectById(Long.parseLong(id));
        if(CommonUtil.isEmpty(sdcCdssItemEntity)){
            return sdcCdssItemEntity;
        }
        String temp = StringEscapeUtils.unescapeHtml(sdcCdssItemEntity.getShowPremise());
        sdcCdssItemEntity.setShowPremise(temp);
        return sdcCdssItemEntity;
    }

    @RequestMapping("/to_addRule")
    public String to_addRule(Model model) {
        JSONObject standSourceMap = sdsStandSourceService.getDataMap();
        model.addAttribute("dataSourceMap", standSourceMap);
        return PREFIX + "sdctreatplan_addshowpremise.html";
    }

    @RequestMapping(value = "/addShowPremise")
    @ResponseBody
    public Object addShowPremise(SdcShowPremiseEntity sdcShowPremise) {
        if (CommonUtil.isOneEmpty(sdcShowPremise)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            sdcShowPremise.setOperator1(java.net.URLDecoder.decode(sdcShowPremise.getOperator1(), "UTF-8"));
            sdcShowPremise.setOperator2(java.net.URLDecoder.decode(sdcShowPremise.getOperator2(), "UTF-8"));
            sdcShowPremise.setParam1(java.net.URLDecoder.decode(sdcShowPremise.getParam1(), "UTF-8"));
            sdcShowPremise.setParam2(java.net.URLDecoder.decode(sdcShowPremise.getParam2(), "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(sdcShowPremise.getId())) {
            sdcShowPremise.insert();
        } else {
            SdcShowPremiseEntity old = this.sdcShowPremiseService.selectById(sdcShowPremise.getId());
            old.setExpCode(sdcShowPremise.getExpCode());
            old.setRuleDesc(sdcShowPremise.getRuleDesc());
            old.setRuleMemo(sdcShowPremise.getRuleMemo());
            old.setParam1(sdcShowPremise.getParam1());
            old.setParam2(sdcShowPremise.getParam2());
            old.setOperator1(sdcShowPremise.getOperator1());
            old.setOperator2(sdcShowPremise.getOperator2());
            old.setDataSource1(sdcShowPremise.getDataSource1());
            old.setDataSource2(sdcShowPremise.getDataSource2());
            old.setDataSourceItem1(sdcShowPremise.getDataSourceItem1());
            old.setDataSourceItem2(sdcShowPremise.getDataSourceItem2());
            old.setRuleType(sdcShowPremise.getRuleType());
            old.setDefaultValue(sdcShowPremise.getDefaultValue());

            old.updateAllColumnById();
        }

        return R.ok();
    }

    @RequestMapping(value = "/showPremise")
    @ResponseBody
    public Object showPremise(@RequestParam Map<String, Object> params) {
        SdcShowPremiseEntity sdcShowPremiseEntity = new SdcShowPremiseEntity();
        if (!StringUtils.isEmpty(params.get("id"))) {
            String id = (String) params.get("id");
            sdcShowPremiseEntity = sdcShowPremiseService.selectById(Long.parseLong(id));
        }
        return sdcShowPremiseEntity;
    }

    @RequestMapping("/to_updateRule")
    public String toUpdateRule(@RequestParam Map<String, Object> params, Model model) {
        JSONObject standSourceMap = sdsStandSourceService.getDataMap();
        model.addAttribute("dataSourceMap", standSourceMap);
        model.addAttribute("sdcQcRuleId", params.get("sdcQcRuleId"));
        return PREFIX + "sdctreatplan_editshowpremise.html";
    }

    @RequestMapping(value = "/cancelRule")
    @ResponseBody
    public Object cancelRule(@RequestParam Long sdcQcRuleId) {

        this.sdcShowPremiseService.deleteById(sdcQcRuleId);

        return R.ok();
    }

    @RequestMapping(value = "/addTimeQuantum")
    @ResponseBody
    public Object addTimeQuantum(TreatPlanDto treatPlanDto) {
        if (CommonUtil.isOneEmpty(treatPlanDto)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        if (CommonUtil.isEmpty(treatPlanDto.getId())) {
            SdcCdssItemEntity sdcCdssItemEntity = new SdcCdssItemEntity();
            sdcCdssItemEntity.setData(treatPlanDto.getDataId());
            sdcCdssItemEntity.setDic(treatPlanDto.getDicId());
            sdcCdssItemEntity.setGetTiming(treatPlanDto.getGetTiming());
            sdcCdssItemEntity.setPushStart(treatPlanDto.getPushEnd());
            sdcCdssItemEntity.setPushEnd(treatPlanDto.getPushEnd());
            sdcCdssItemEntity.setTimeUnit(treatPlanDto.getTimeUnit());
            sdcCdssItemEntity.insert();
        } else {
            SdcCdssItemEntity old = sdcCdssItemService.selectById(treatPlanDto.getId());
            old.setData(treatPlanDto.getDataId());
            old.setDic(treatPlanDto.getDicId());
            old.setGetTiming(treatPlanDto.getGetTiming());
            old.setPushStart(treatPlanDto.getPushStart());
            old.setPushEnd(treatPlanDto.getPushEnd());
            old.setTimeUnit(treatPlanDto.getTimeUnit());
            old.updateAllColumnById();
        }

        return R.ok();
    }
}
